import { App } from "vue";
import Mediator from "./mediator";

declare module "vue" {
  interface ComponentCustomProperties {
    $localStorage: Storage;
    $on: (key: string, callback: (...args: unknown[]) => void) => void;
  }
}

const keys: string[] = [];

const sub = new Mediator();

export const LocalStorage = {
  install: (app: App<Element>) => {
    console.log(app);
    // 在这里编写插件代码
    // 注入一个全局可用的 $translate() 方法
    app.config.globalProperties.$on = (
      key: string,
      callback: (...args: unknown[]) => void,
    ) => {
      sub.subscribe(key, callback);
    };
    app.config.globalProperties.$localStorage = {
      getItem: (key: string) => {
        return window.localStorage.getItem(key);
      },

      setItem: (key: string, value: any) => {
        // 防止重复发布
        if (!keys.includes(key)) keys.push(key);

        // 被修改就发布事件
        sub.publish(key, value);

        return window.localStorage.setItem(key, value);
      },
      clear: () => {
        // 被删除就每个key发布事件
        keys.map((key) => sub.publish(key, undefined));
        // 发布后清空记录key的数组
        keys.length = 0;

        return window.localStorage.clear();
      },
      removeItem: (key: string) => {
        keys.splice(keys.indexOf(key), 1);

        // 被移除就发布 undefined
        sub.publish(key, undefined);

        return () => window.localStorage.removeItem(key);
      },
      key: window.localStorage.key,
      length: window.localStorage.length,
    };
  },
};
